package cn.farm.farm.Controller.CommonController;

import cn.farm.farm.MessageModel.Common;
import cn.farm.farm.MessageModel.StringCommon;
import cn.farm.farm.Util.FileUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController()
public class PhotoSolrController {

    public final String tempPath = "C:\\Users\\Administrator\\Desktop\\BaiduImage\\";

    public static final String APP_ID = "16125382";
    public static final String API_KEY = "RTospIA7c9NeaV3FmjqdSCbv";
    public static final String SECRET_KEY = "N7uHz10mk0yXoq34qLA5b7sD5MoQf3Ua";

    private String url= "http://v475n8.natappfree.cc/infer";

    @PostMapping(value = "farm/common/plant/dealImage",produces = "application/problem+json;charset=UTF-8")
    public Common dealPhoto(@RequestParam(value = "photo") MultipartFile image) throws IOException {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd-HH-mm-ss");
        String time = simpleDateFormat.format(date);
        String path = tempPath+time+""+image.toString()+".png";
        try {
            FileUtil.download(image,path);
        } catch (IOException e) {
            e.printStackTrace();
            return new Common(500,"server error");
        }
//        AipImageClassify client = new AipImageClassify(APP_ID, API_KEY, SECRET_KEY);
//        org.json.JSONObject res = client.plantDetect(path, new HashMap<String, String>());
//        String json = res.toString();
//        System.out.println(json);


        HttpClient client=new HttpClient();
        MultipartPostMethod postMethod=new MultipartPostMethod (url);
        FilePart filePart = new FilePart("img", new File(path));//文件参数
        postMethod.addPart(filePart);
        //修改请求的头部
        postMethod.setRequestHeader("Content-Type", "file/jpeg,file/gif,file/png; charset=utf-8");
        //4.执行请求 ,结果码
        int code=client.executeMethod(postMethod);
        if(code==404){
           return new Common(400,"error");
        }System.out.println("结果码:"+code);
        //5. 获取结果
        String plantName =postMethod.getResponseBodyAsString();
        System.out.println("Post请求的结果："+plantName);
        return new StringCommon(200,plantName,plantName);
    }


}
